<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>参数配置</span>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增
            </el-button>
            <el-button type="success" @click="refreshList">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="参数名称">
          <el-input v-model="queryParams.name" placeholder="请输入参数名称" clearable @keyup.enter="searchList" />
        </el-form-item>
        <el-form-item label="参数键名">
          <el-input v-model="queryParams.key" placeholder="请输入参数键名" clearable @keyup.enter="searchList" />
        </el-form-item>
        <el-form-item label="参数类型">
          <el-select v-model="queryParams.type" placeholder="请选择参数类型" clearable>
            <el-option label="系统参数" value="system" />
            <el-option label="业务参数" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 参数表格 -->
      <el-table v-loading="loading" :data="configList" border>
        <el-table-column prop="id" label="参数ID" width="80" />
        <el-table-column prop="name" label="参数名称" width="150" />
        <el-table-column prop="key" label="参数键名" width="150" />
        <el-table-column prop="value" label="参数值" show-overflow-tooltip />
        <el-table-column prop="type" label="参数类型" width="100">
          <template #default="scope">
            <el-tag :type="row.type === 'system' ? 'danger' : 'success'">
              {{ row.type === 'system' ? '系统参数' : '业务参数' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否内置" width="80">
          <template #default="scope">
            <el-tag :type="row.is_built_in ? 'danger' : 'info'">
              {{ row.is_built_in ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button
              v-if="!row.is_built_in"
              type="danger"
              size="small"
              @click="handleDelete(row.id)"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 参数配置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
      @closed="resetForm"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="key">
          <el-input v-model="configForm.key" placeholder="请输入参数键名" :disabled="isEdit && configForm.is_built_in" />
        </el-form-item>
        <el-form-item label="参数值" prop="value">
          <el-input
            v-model="configForm.value"
            type="textarea"
            :rows="4"
            placeholder="请输入参数值"
          />
        </el-form-item>
        <el-form-item label="参数类型" prop="type">
          // 修改后（显式声明value属性）
          <el-radio-group v-model="configForm.type">
            <el-radio :value="'system'">系统参数</el-radio>
            <el-radio :value="'business'">业务参数</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="isEdit" label="是否内置">
          <el-switch
            v-model="configForm.is_built_in"
            disabled
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="configForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getConfigList,
  getConfigDetail,
  addConfig,
  editConfig,
  deleteConfig
} from '@/api/system'
import {
  Plus, Refresh, Search, Edit, Delete
} from '@element-plus/icons-vue'

// 列表数据
const configList = ref([])
const total = ref(0)
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  name: '',
  key: '',
  type: '',
  page: 1,
  pageSize: 10
})

// 表单相关
const configFormRef = ref(null)
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑参数' : '新增参数')

// 表单数据
const configForm = reactive({
  id: undefined,
  name: '',
  key: '',
  value: '',
  type: 'business',
  is_built_in: false,
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
  key: [
    { required: true, message: '参数键名不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_\.]+$/, message: '参数键名只能包含字母、数字、下划线和点', trigger: 'blur' }
  ],
  value: [{ required: true, message: '参数值不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '参数类型不能为空', trigger: 'change' }]
}

// 初始化
onMounted(() => {
  getList()
})

// 获取参数列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getConfigList(queryParams)
    configList.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    console.error(error)
    ElMessage.error('获取参数列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  getList()
}

// 搜索列表
const searchList = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.key = ''
  queryParams.type = ''
  queryParams.page = 1
  getList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 点击新增按钮
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 点击编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getConfigDetail(row.id)
    Object.assign(configForm, res.data)
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error(error)
    ElMessage.error('获取参数详情失败')
  }
}

// 点击删除按钮
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该参数吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteConfig(id)
      ElMessage.success(res.msg || '删除成功')
      getList()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
  
  Object.assign(configForm, {
    id: undefined,
    name: '',
    key: '',
    value: '',
    type: 'business',
    is_built_in: false,
    remark: ''
  })
}

// 提交表单
const submitForm = () => {
  configFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEdit.value) {
        const res = await editConfig(configForm)
        ElMessage.success(res.msg || '修改成功')
      } else {
        const res = await addConfig(configForm)
        ElMessage.success(res.msg || '添加成功')
      }
      
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error(error)
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 